<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="ch-CN">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../static/bootstrap-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/layui/css/layui.css">
    <style>
        .top:after {
            display: block;
            content: "";
            clear: both;
        }

        .layui-form-label {
            width: 100px;
        }

        .container {
            margin-top: 4%;
        }

        .ceng {
            width: 180px;
            height: 180px;
            background-color: rgba(0, 0, 0, 0.3);
            position: absolute;
            display: none;
            text-align: center;
            line-height: 180px;
            color: white;
            cursor: pointer;
        }

        #pic:hover .ceng {
            display: block;
        }

        #file {
            width: 100%;
            height: 100%;
            position: absolute;
            z-index: 1000;
            border: 1px solid red;
            opacity: 0;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="container" style="display: none" id="form">
    <div class="top pt-2 m-auto">
        <form class="layui-form" action="" enctype="multipart/form-data">
            <div class="t_left float-left" style="margin-left:90px;width: 20%;height: 200px;">
                <div id="pic"
                     style="position: relative; overflow:hidden; border-radius: 50%;margin: 0 auto;width: 180px; height: 180px;background-color: #9fcdff">
                    <div class="ceng">
                        <span>修改头像</span>
                    </div>
                    <input id="file" type="file">
                    <img id="img_p" width="180px" height="180px"
                         src="https://s1.hdslb.com/bfs/static/jinkela/space/assets/icon-auth.png"
                         alt="">
                </div>

                <p class="text-center pt-2 layui-font-12"><span style="color: red">* </span>图片大小不能超过<span style="text-decoration: underline">300KB</span></p>

            </div>
            <div class="t_right float-right" style="width: 70%;">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline" style="width: 70%">
                        <input type="text" name="userName" id="userName" required lay-verify="required"
                               placeholder="请输入用户名" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">ID</label>
                    <div class="layui-input-inline" style="width: 70%">
                        <input type="text" id="u_id" readonly disabled style="border: none" name="u_id" required
                               lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">创建日期</label>
                    <div class="layui-input-inline" style="width: 70%">
                        <input disabled id="date" readonly type="text" name="userDate" required lay-verify="required"
                               placeholder="请选择日期" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">绑定手机号</label>
                    <div class="layui-input-inline" style="width: 70%">
                        <input type="text" id="userPhone" name="userPhone" required lay-verify="required"
                               placeholder="请输入手机号" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">绑定邮箱</label>
                    <div class="layui-input-inline" style="width: 70%">
                        <input type="email" id="userEmail" readonly name="userEmail" required lay-verify="required"
                               placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button id="edit" class="layui-btn layui-btn-normal" lay-submit lay-filter="userEdit">修改
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

</div>

<script src="../static/bootstrap-dist/js/jquery-3.5.1.js"></script>
<script src="../static/layui/layui.js"></script>
<script !src="">
    $(function () {
        layui.use(['table', 'layer', 'laydate', 'form'], function () {
            let table = layui.table;
            let layer = layui.layer;
            let laydate = layui.laydate;
            let form = layui.form;

            let index;
            let img_base64;
            $.ajax({
                url: "user",
                data: {
                    "opr": "getUser"
                },
                method: "post",
                dataType: "json",
                beforeSend: function () {
                    index = layer.load(2); //换了种风格
                },
                complete: function () {
                    layer.close(index);
                    $("#form").fadeIn(500);
                },
                success: function (data) {
                    $("#userName").val(data.username);
                    $("#u_id").val(data.id);
                    $("#date").val(data.creatDate);
                    $("#userPhone").val(data.phoneNumber);
                    $("#userEmail").val(data.userEmail);
                    img_base64 = data.userImg;
                    $("#img_p").attr("src", img_base64);
                },
                error: function () {
                    layer.alert("获取失败");
                    $("#edit").hide();
                }
            });

            form.on('submit(userEdit)', function (data) {
                if (verifyEmail(data.field.userEmail)) {
                    let index;

                    $.ajax({
                        url: "user",
                        method: "post",
                        data: {
                            "opr": "editSave",
                            "id": data.field.u_id,
                            "userName": data.field.userName,
                            "creatDate": data.field.userDate,
                            "phone": data.field.userPhone,
                            "userEmail": data.field.userEmail,
                            "userImg": img_base64
                        }, beforeSend: function () {
                            index = layer.load(2); //换了种风格
                        },
                        complete: function () {
                            layer.close(index);
                            $("#form").fadeIn(500);
                        },
                        success: function (data) {
                            if (data == "true") {
                                layer.alert(
                                    '修改完成',
                                    {icon: 1},
                                    function () {
                                        parent.location.reload();
                                    });
                            } else {
                                layer.alert('修改失败', {icon: 2});
                            }
                        }
                    })
                } else {
                    layer.alert("邮箱格式不正确")
                }
                return false;
            });


            $('#file').change(function () {
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test($('#file').val())) {
                    layer.alert("图片类型必须是.gif,jpeg,jpg,png中的一种", {title: '类型错误'});
                    $('#file').val("")
                    return;
                }

                var file = $('#file').get(0).files[0];

                if (file.size / 1024 > 300){
                    layer.alert("图片文件不能超过300KB")
                    console.log(file.size / 1024)
                    return;
                }

                let maxWidth = 500;
                let maxHeight = 500;
                base64ThumbImage(file,maxWidth,maxHeight);

                /*//创建用来读取此文件的对象
                var reader = new FileReader();
                //使用该对象读取file文件
                reader.readAsDataURL(file);
                //读取文件成功后执行的方法函数

                reader.onload = function (e) {
                    //读取成功后返回的一个参数e，整个的一个进度事件
                    //选择所要显示图片的img，要赋值给img的src就是e中target下result里面
                    //的base64编码格式的地址
                    $('#img_p').get(0).src = e.target.result;
                    img_base64 = e.target.result;
                }*/
            });

            function base64ThumbImage(elementObj,maxWidth,maxHeight){
                try {
                    var file = elementObj;
                    var reader = new FileReader(),
                        img = new Image();
                    reader.readAsDataURL(file);
                    reader.onload = function(e) {
                        img.src = e.target.result;
                    };
                    img.onload = function () {
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        var originWidth = this.width;
                        var originHeight = this.height;
                        var targetWidth = originWidth,targetHeight = originHeight;
                        if(originWidth > maxWidth || originHeight > maxHeight) {
                            if(originWidth / originHeight > maxWidth / maxHeight) {
                                targetWidth = maxWidth;
                                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                            } else {
                                targetHeight = maxHeight;
                                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                            }
                        }
                        canvas.width = targetWidth;
                        canvas.height = targetHeight;
                        context.clearRect(0, 0, targetWidth, targetHeight);
                        context.drawImage(img, 0, 0, targetWidth, targetHeight);
                        var base64_url = canvas.toDataURL('image/jpeg', 0.92);//base64 格式
                        $('#img_p').get(0).src = base64_url;
                        img_base64 = base64_url;

                        console.log(base64_url);
                    }
                } catch (e) {
                    alert('图片转Base64出错啦！' + e.toString())
                }
            }
        })
    });

    function verifyEmail(email) {
        let t = /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
        if (!(t.test(email))) {
            return false;
        } else {
            return true;
        }
    }

</script>
</body>
</html>